<?php defined('SYSPATH') or die('No direct script access.');
 
class Model_Functions extends ORM {
	protected $_table_name = 'menu';
	public $result = array();

	public function get_sitemap() {
		$main_menu = Model::factory('Menu')->get_all_by_location(0);
		$left_menu = Model::factory('Menu')->get_all_by_location(1);
		$main_menu = $this->prepare_your_array($main_menu, 0);
		$left_menu = $this->prepare_your_array($left_menu, 0);

		return array(
			array(
				'title' => 'Главная',
				'link' => URL::base(),
				'childrens' => array(
					array(
						'title' => 'Посты',
						'link' => URL::site('posts'),
					),
					array(
						'title' => 'Главное меню',
						'link' => 'javascript:void(0)',
						'type' => 'menu',
						'childrens' => $main_menu
					),
					array(
						'title' => 'Меню слева',
						'link' => 'javascript:void(0)',
						'type' => 'menu',
						'childrens' => $left_menu
					),
					array(
						'title' => 'Карта сайта',
						'link' => URL::site('sitemap'),
					),
				)
			)
		);
	}

	public function prepare_your_array($array, $parent_id, $lvl = 0) {
		$result = array();

		foreach ($array as $key => $item) {
			if ($item['parent_id'] == $parent_id) {
				$result[$key]['title'] = $item['title'];
				$result[$key]['link'] = $item['link'];
				unset($array[$key]);

				$result[$key]['childrens'] = $this->prepare_your_array($array, $item['id'], $lvl+1);
			}
		}

		return $result;

	}

}